package com.xiguaji.tiktok.task.aweme.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.gugee.tiktok.common.model.spider.aweme.Aweme_list;
import com.gugee.tiktok.common.model.spider.aweme.BloggerAwemesResponse;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.EventBusTemplate;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import com.xiguaji.tiktok.task.aweme.spider.AwemeSpiderClient;

import java.time.LocalDateTime;
import java.util.stream.Collectors;

import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class    SaveBloggerAwemeEventListener implements IEventListener<SaveBloggerAwemeEventListener.SaveBloggerAwemeEvent> {

    @Autowired
    @Lazy
    EventBusTemplate eventBusTemplate;

    @Autowired
    AwemeSpiderClient awemeSpiderClient;

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(SaveBloggerAwemeEvent event) {
        long start = System.currentTimeMillis();
        event.uids.forEach(uid -> {
            try {
                run(event, uid);
            } catch (Exception ex) {
                XxlJobLogger.log(ex);
                log.error("SaveBloggerAweme error. uid:" + uid+ex.getMessage());
            }
        });
//        XxlJobLogger.log("SaveBloggerAwemeEvent  end cost total={}" ,(System.currentTimeMillis()-start)/1000);
    }

    private void run(SaveBloggerAwemeEvent event, long uid) {
        long max_cursor = 0;
        int count = 40;
        boolean isHasMore = true;
        List<Aweme_list> awemes = new ArrayList<>();
        long totalStart = System.currentTimeMillis();
        int spiderFails=0;
        try {
            long condition = DateTimeUtils.second(LocalDateTime.now().minusDays(92));

            while (isHasMore) {
                long start = System.currentTimeMillis();
                BloggerAwemesResponse response = awemeSpiderClient.getBloggerAwemes(uid, max_cursor, count);
                if (response == null || CollectionUtils.isEmpty(response.getAweme_list())) break;
                isHasMore = response.isHas_more();
                max_cursor = response.getMax_cursor();
                //如果属于最近90天的列表则收录
                awemes.addAll(response.getAweme_list().stream()
                        .filter(a -> a.getCreate_time() > condition)
                        .collect(Collectors.toList()));
                //awemeSpiderClient.getBloggerAwemes，目前response.getMax_cursor()最多返回33个，count大于33不起效果
                if (response.getMax_cursor() <= condition * 1000) {
                   break;
                }
            }
            if((System.currentTimeMillis()-totalStart)/1000>5) {
                log.info("SaveBloggerAwemeEventListener blogger: " + uid + "awemes.size="+awemes.size()+", total awemeSpiderClient.getBloggerAwemes use time:" + (System.currentTimeMillis() - totalStart) / 1000 + "s");
            }

        } catch (Exception ex) {
            //记录异常，继续进行接下去的操作
            log.error(event.getSource() + " uid:" + uid + " count:" + awemes.size(), ex);
            spiderFails++;
            XxlJobLogger.log(ex);

        }

        if (awemes.size() > 0) {
            event.awemeSize=awemes.size();
            event.awemeSpiderBloggerAwemes=(System.currentTimeMillis()-totalStart)/1000;

            var saveAwemeEvent = new SaveAwemeEventListener.SaveAwemeEvent(uid, awemes, SaveAwemeEventListener.RefreshAwemeCommentType.IGNORE);


//            try {
//                Thread t=  new Thread(()->{
                    eventBusTemplate.post(saveAwemeEvent);
//                    }
//                );
//                t.start();
//                t.join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            event.saveAwemeTimeStatistics=saveAwemeEvent.getSaveAwemeTimeStatistics();

        }else{
            log.error(event.getSource() + " 无视频Spider uid:" + uid + " spiderFails:" + spiderFails);
//            XxlJobLogger.log("SaveBloggerAwemeEvent  getBloggerAwemes totalcost={},uid={},awemes.size=0 ******" ,(System.currentTimeMillis()-totalStart)/1000,uid);

        }
        //log.info(event.getSource() + " uid:" + uid + " count:" + awemes.size());
    }

    public static class SaveBloggerAwemeEvent extends Event {

        public SaveBloggerAwemeEvent(List<Long> uids) {
            this(null, uids);
        }

        public SaveBloggerAwemeEvent(Event event, List<Long> uids) {
            super(event, "SaveBloggerAweme");
            this.uids = uids;
        }
        //用于日志打印和统计awemeSize更新情况
        //要更新的视频数
        private int awemeSize=0;
        private long awemeSpiderBloggerAwemes=0;
        private SaveAwemeEventListener.SaveAwemeTimeStatistics saveAwemeTimeStatistics;
        private List<Long> uids;
        public int getAwemeSize(){
            return awemeSize;
        }

        public long getAwemeSpiderBloggerAwemes() {
            return awemeSpiderBloggerAwemes;
        }

        public SaveAwemeEventListener.SaveAwemeTimeStatistics getSaveAwemeTimeStatistics() {
            return saveAwemeTimeStatistics;
        }
    }
}
